package com.study.other;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.jetbrains.annotations.NotNull;

/**
 * @Author tanglingyu
 * @Date: 2021/05/26/ 9:41
 * @Description:自定义线程池和自定义拒绝策略
 */
public class MyThreadPoolExecutor {

  private ThreadPoolExecutor pool = null;

  public void init() {
    pool = new ThreadPoolExecutor(1,
        3, 5, TimeUnit.MINUTES, new ArrayBlockingQueue<Runnable>(5)
        , new CustomThreadFactory(), new CustomRejectionExecutionHandler());
  }

  public void destroy() {
    if (pool != null) {
      pool.shutdown();
    }
  }

  public ExecutorService getMyThreadPoolExecutor() {
    return this.pool;
  }


  /**
   * 自定义创建线程工厂
   */
  private class CustomThreadFactory implements ThreadFactory {

    private AtomicInteger counter = new AtomicInteger(0);

    @Override
    public Thread newThread(@NotNull Runnable r) {
      Thread t = new Thread(r);
      String threadName = MyThreadPoolExecutor.class.getSimpleName() + counter.addAndGet(1);
      t.setName(threadName);
      return t;
    }
  }

  /**
   * 自定义拒绝策略
   */
  private class CustomRejectionExecutionHandler implements RejectedExecutionHandler {

    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
      try {
        //核心改造点,由blockingqueue的offer改成put阻塞方法
        executor.getQueue().put(r);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  public static void main(String[] args) {
    MyThreadPoolExecutor exec = new MyThreadPoolExecutor();
    //初始化
    exec.init();
    ExecutorService pool = exec.getMyThreadPoolExecutor();
    Mytask task = new Mytask();
    for (int i = 0; i < 1000; ++i) {
      pool.execute(task);
    }
    try {
      Thread.sleep(5000);
      //销毁----留点时间给线程池执行,因为任务没有提交执行完,如果销毁线程池,任务也就无法执行了
      exec.destroy();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

  }

}

class Mytask implements Runnable {

  public AtomicInteger i = new AtomicInteger(0);

  @Override
  public void run() {
    System.out.println("第" + i.getAndIncrement() + "次执行任务");
  }
}
